<template>
  <!--用户新增/修改Modal-->
  <a-modal
    :title="isAdd? '用户新增':'用户修改'"
    :width="width"
    :visible="visible"
    :confirmLoading="confirmLoading"
    @ok="handleModalOk"
    @cancel="handleModalCancel"
  >
    <a-form :form="form">
      <a-form-item
        label="隐藏的参数"
        :label-col="labelCol"
        :wrapper-col="wrapperCol"
        style="display: none"
      >
        <a-input v-decorator="[`id`,{initialValue: userFmt.id}]" />
      </a-form-item>
      <a-row :gutter="24">
        <a-col :span="12">
          <a-form-item
            label="用户名"
            :label-col="labelCol"
            :wrapper-col="wrapperCol"
          >
            <a-input
              v-decorator="[
                'username',
                {
                  initialValue: userFmt.username,
                  rules: [
                    {
                      required: true,
                      message: '请输入用户名'
                    },
                    {
                      validator: usernameValidator
                    }
                  ]
                }
              ]"
              placeholder="请输入用户名"
              :allowClear="true"
              :disabled="!isAdd"
            />
          </a-form-item>
        </a-col>
        <a-col :span="12">
          <a-form-item
            label="昵称"
            :label-col="labelCol"
            :wrapper-col="wrapperCol"
          >
            <a-input
              v-decorator="[
                'nickname',
                {
                  initialValue: userFmt.nickname,
                  rules: [
                    {
                      required: true,
                      message: '请输入昵称'
                    }
                  ]
                }
              ]"
              placeholder="请输入昵称"
              :allowClear="true"
            />
          </a-form-item>
        </a-col>
        <a-col :span="12">
          <a-form-item
            label="输入密码"
            :label-col="labelCol"
            :wrapper-col="wrapperCol"
          >
            <a-input-password
              v-decorator="[
                'password',
                {
                  initialValue: userFmt.password,
                  rules: [
                    {
                      required: true,
                      message: '请输入密码'
                    },
                    {
                      validator: passwordValidator
                    }
                  ]
                }
              ]"
              placeholder="请输入密码"
              :allowClear="true"
              type="password"
              :disabled="!isAdd"
            />
          </a-form-item>
        </a-col>
        <a-col :span="12">
          <a-form-item
            label="状态"
            :label-col="labelCol"
            :wrapper-col="wrapperCol"
          >
            <a-select
              v-decorator="['state', {initialValue: userFmt.state}]"
              placeholder="请选择状态"
            >
              <a-select-option value="1">启用</a-select-option>
              <a-select-option value="0">禁用</a-select-option>
              <a-select-option value="2">锁定</a-select-option>
            </a-select>
          </a-form-item>
        </a-col>
        <a-col :span="12">
          <a-form-item
            label="手机号码"
            :label-col="labelCol"
            :wrapper-col="wrapperCol"
          >
            <a-input
              v-decorator="[
                'phone',
                {
                  initialValue: userFmt.phone,
                  rules: [
                    {
                      required: true,
                      message: '请输入手机号码'
                    },
                    {
                      validator: phoneValidator
                    }
                  ]
                }
              ]"
              placeholder="请输入手机号码"
              :allowClear="true"
              :disabled="!isAdd"
            />
          </a-form-item>
        </a-col>
        <a-col :span="12">
          <a-form-item
            label="用户性别"
            :label-col="labelCol"
            :wrapper-col="wrapperCol"
          >
            <a-radio-group
              v-decorator="['gender', {initialValue: userFmt.gender }]"
              placeholder="请选择性别"
            >
              <a-radio value="1">男</a-radio>
              <a-radio value="0">女</a-radio>
            </a-radio-group>
          </a-form-item>
        </a-col>
        <a-col :span="12">
          <a-form-item
            label="用户角色"
            :label-col="labelCol"
            :wrapper-col="wrapperCol"
          >
            <a-select
              v-decorator="[
                'roleId',
                {
                  initialValue: userFmt.roleId,
                  rules: [{ required: true, message: '请选择角色!' }]
                }
              ]"
              placeholder="请选择角色"
            >
              <a-select-option v-for="d in roleSelect" :key="d.id">
                {{ d.name }}
              </a-select-option>
            </a-select>
          </a-form-item>
        </a-col>
        <a-col :span="12">
          <a-form-item
            label="部门"
            :label-col="labelCol"
            :wrapper-col="wrapperCol">
            <a-tree-select
              v-decorator="[
                'departmentCode',
                {
                  initialValue: userFmt.departmentCode,
                  rules: [{ required: true, message: '请选择所属部门!' }]
                }
              ]"
              placeholder="请选择所属部门"
              style="width: 100%"
              :dropdown-style="{ maxHeight: '400px', overflow: 'auto' }"
              :treeData="treeFmt"
              :allowClear="true"
            >
            </a-tree-select>
          </a-form-item>
        </a-col>
        <a-col :span="24">
          <a-form-item
            label="备注"
            :label-col="{
              xs: { span: 6 },
              sm: { span: 3 }
            }"
            :wrapper-col="{
              xs: { span: 18 },
              sm: { span: 21 }
            }"
          >
            <a-textarea
              :rows="3"
              v-decorator="[
                'remark',
                { initialValue: user.remark }
              ]"
            />
          </a-form-item>
        </a-col>
      </a-row>
    </a-form>
  </a-modal>
</template>

<script>
import api from '../system.js'
import { emptyObject, phoneRule, passwordRule, usernameRule } from '@/utils/samsUtil'
import { treeConvert } from '@/utils/antUtil'

// 用户新增/修改Modal
export default {
  name: 'UserModalModify',
  data () {
    return {
      isAdd: true,
      visible: false,
      confirmLoading: false,
      width: 1000,
      form: this.$form.createForm(this),
      labelCol: {
        xs: { span: 12 },
        sm: { span: 6 }
      },
      wrapperCol: {
        xs: { span: 12 },
        sm: { span: 18 }
      },
      user: {},
      roleSelect: [],
      treeData: []
    }
  },
  computed: {
    treeFmt () {
      let { treeData } = this
      treeData = treeData || []
      const tree = treeConvert(treeData)
      return tree
    },
    userFmt () {
      let { user } = this
      user = user || {}
      const fmt = {
        ...user,
        gender: user.gender === 0 ? '0' : '1',
        state: user.gender === 0 ? '0' : '1'
      }
      return fmt
    }
  },
  created () {
    this.queryDepartmentTree()
    this.queryRoleList()
  },
  methods: {
    // Modal show
    showModal (param = {}) {
      this.restForm()
      if (emptyObject(param.id)) {
        // 新增 isAdd=true 展示密码框
        this.isAdd = true
      } else {
        // 修改  isAdd=false 不展示密码框
        this.isAdd = false
        // this.form.setFieldsValue({'password':'112233@qq'})
        param['password'] = '112233@qq'
      }
      this.user = param
      this.visible = true
    },
    // Modal hide
    hideModal () {
      this.visible = false
    },
    // Modal 确定按钮--保存
    handleModalOk () {
      this.form.validateFields((error, values) => {
        if (error === null) {
          let url = api.user.add
          if (values.id) {
            url = api.user.update
            delete values.password
            delete values.username
            delete values.phone
          }
          this.axios.post(url, values)
            .then((response) => {
              if (response.code === 200) {
                this.$message.success('保存成功')
                this.$emit('refresh')
                this.hideModal()
              } else {
                this.$message.error('保存失败：' + response.message)
              }
            })
            .catch((error) => {
              this.$message.error('保存异常' + error)
            })
        } else {
          this.$message.error('提交异常，请检查是否有参数未校验成功')
        }
      })
    },
    // Modal 取消按钮
    handleModalCancel () {
      this.hideModal()
    },
    // Form 表单数据初始化方法 还原
    restForm () {
      this.form.resetFields()
    },
    // 获取组织结构树
    queryDepartmentTree () {
      this.axios.post(api.department.getDepartmentTree)
        .then((res) => {
          this.treeData = res.data
        })
        .catch((error) => {
          console.log('请求异常...', error)
        })
    },
    // 获取角色list
    queryRoleList () {
      this.axios.post(api.role.getList)
        .then((response) => {
          this.roleSelect = response.data
        })
        .catch((error) => {
          console.log('【角色下来】获取数据请求异常了', error)
        })
    },
    // 校验-手机号码校验
    phoneValidator (rule, value, callback) {
      // 若是修改放弃校验，暂时不允许修改手机号码
      if (!this.isAdd) {
        callback()
        return
      }
      if (emptyObject(value)) {
        callback()
        return
      }
      const b = phoneRule(value)
      if (!b) {
        // eslint-disable-next-line
        callback('请输入有效的手机号码')
      } else {
        callback()
      }
    },
    // 校验-密码校验
    passwordValidator (rule, value, callback) {
      if (emptyObject(value)) {
        callback()
        return
      }
      const b = passwordRule(value)
      if (!b) {
        // eslint-disable-next-line
        callback('必须包含数字、特殊符号、字母，长度8-16')
      } else {
        callback()
      }
    },
    // 校验-用户名校验
    usernameValidator (rule, value, callback) {
      if (emptyObject(value)) {
        callback()
        return
      }
      const b = usernameRule(value)
      if (!b) {
        // eslint-disable-next-line
        callback('只能由字母、数字、下划线组成，长度5-10')
      } else {
        this.axios.post(api.user.usernameUnique,
          { id: this.form.getFieldValue('id'), username: value })
          .then((response) => {
            if (response.code === 200) {
              callback()
            } else {
              // eslint-disable-next-line
              callback('该用户名已存在')
            }
          })
      }
    }
  }
}
</script>
